import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

public class WxSecCheck {

    public Boolean msgSecCheck (String access_token, String content) {
        String url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token="+access_token;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HashMap<String, String> param = new HashMap<>();
        param.put("content", content);

        HttpEntity<HashMap<String, String>> httpEntity = new HttpEntity<>(param, headers);
        JSONObject jsonObject = new RestTemplate().postForObject(url, httpEntity, JSONObject.class);
        return (Integer) jsonObject.get("errcode") == 0;
    }

    public Boolean imgSecCheck(String access_token, String pics) {
        String url = "https://api.weixin.qq.com/wxa/img_sec_check?access_token="+access_token;
        List<Integer> errcodes = Arrays.asList(pics.split(",")).parallelStream().map(picUrl -> {
            try {
                if (org.springframework.util.StringUtils.isEmpty(picUrl)) return 87014;
                URLConnection connection = new URL(picUrl).openConnection();
                InputStream inputStream = connection.getInputStream();
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                byte[] bytes = new byte[1024];
                int len;
                while ((len = inputStream.read(bytes)) > 0) outStream.write(bytes, 0, len);
                inputStream.close();
                outStream.close();

                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                HttpEntity requestEntity = new HttpEntity(outStream.toByteArray(), headers);
                JSONObject jsonObject = JSON.parseObject(new RestTemplate().postForObject(url, requestEntity, String.class));
                return (Integer) jsonObject.get("errcode");
            } catch (IOException e) {
                e.printStackTrace();
                return 87014;
            }
        }).collect(Collectors.toList());
        return ! errcodes.parallelStream().anyMatch(errcode -> errcode == 87014);
    }

}
